// pre-submit callback
function showRequest(formData, jqForm, options) {
  generateUploadJSONRequest();

  /*
  // formData is an array; here we use jQuery.param to convert it to a string to display it
  // but the form plugin does this for you automatically when it submits the data
  var queryString = jQuery.param(formData);

  // jqForm is a jQuery object encapsulating the form element.  To access the
  // DOM element for the form do this:
  // var formElement = jqForm[0];

  alert('About to submit: \n\n' + queryString);
  */

  // here we could return false to prevent the form from being submitted;
  // returning anything other than false will allow the form submit to continue
  return true;
}

// post-submit callback
function showResponse(responseJSON, statusText)  {
  if (statusText == 'success') {
    if (responseJSON.error == 1) {
      alert(responseJSON.msg);
      return false;
    } else {
      // File uploaded successfully
      jQuery('#divBulkUpload').dialog('close');
      jQuery('#divBulkDataMapping').dialog('open');

      updateMappingUI(responseJSON.filename, responseJSON.data_cols);
    }
  } else {
    alert(statusText);
    return false;
  }
}

function generateUploadJSONRequest() {
  var data = new Object();

  data.action = 'uploadBulkData';
  var params = new Object();

  params.fileElem = 'bulkuploadfile';
  params.delimiter = jQuery('#delimiter').val();
  params.enclosure = jQuery('#enclosure').val();

  data.params = params;

  var request_str = JSON.stringify(data);

  jQuery('#upload_request').val(request_str);
}

function submitBulkUploadForm() {
  clearMessages();

  if (trim(jQuery('input[name=bulkuploadfile]').val()) == '') {
    alert('Please select a file to upload.');
    return false;
  }

  var ajax_options = {
    //target:        '#output2',   // target element(s) to be updated with server response
    beforeSubmit:  showRequest,  // pre-submit callback
    success:       showResponse,  // post-submit callback
    dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type)

    // other available options:
    //url:       url         // override for form's 'action' attribute
    //type:      type        // 'get' or 'post', override for form's 'method' attribute
    //clearForm: true        // clear all form fields after successful submit
    //resetForm: true        // reset the form after successful submit

    // jQuery.ajax options can be used here too, for example:
    //timeout:   3000
  };

  jQuery(this).ajaxSubmit(ajax_options);

  return false;
}

function updateMappingUI(filename, cols) {
  jQuery('#uploaded_filename').val(filename);

  jQuery("#dbCols").removeOption(/./);
  jQuery("#dbCols").addOption(db_cols, false);

  jQuery("#dataCols").removeOption(/./);
  jQuery("#dataCols").addOption(cols, false);

  if (jQuery('#dbCols')[0].options.length == 0 || jQuery('#dataCols')[0].options.length == 0) {
    jQuery('#btnMap').attr("disabled", true);
  }
  else {
    jQuery('#btnMap').attr("disabled", false);
  }

  jQuery("#dbMappedCols").removeOption(/./);
  jQuery("#dataMappedCols").removeOption(/./);
  jQuery('#btnUnmap').attr("disabled", true);
  jQuery('#btnImport').attr("disabled", true);
}

function mapColumns() {
  if (jQuery('#dbCols').selectedOptions().length > 0 && jQuery('#dataCols').selectedOptions().length > 0) {
    moveSelectedOptionToAnotherSelect('dbCols', 'dbMappedCols');
    moveSelectedOptionToAnotherSelect('dataCols', 'dataMappedCols');
  }

  if (jQuery('#dbCols')[0].options.length == 0 || jQuery('#dataCols')[0].options.length == 0) {
    jQuery('#btnMap').attr("disabled", true);
  }
  if (jQuery('#dbMappedCols').selectedOptions().length > 0 && jQuery('#dataMappedCols').selectedOptions().length > 0) {
    jQuery('#btnUnmap').attr("disabled", false);
    jQuery('#btnImport').attr("disabled", false);
  }
}

function unmapColumns() {
  if (jQuery('#dbMappedCols').selectedOptions().length > 0 && jQuery('#dataMappedCols').selectedOptions().length > 0) {
    moveSelectedOptionToAnotherSelect('dbMappedCols', 'dbCols');
    moveSelectedOptionToAnotherSelect('dataMappedCols', 'dataCols');
  }

  if (jQuery('#dbMappedCols')[0].options.length == 0 || jQuery('#dataMappedCols')[0].options.length == 0) {
    jQuery('#btnUnmap').attr("disabled", true);
    jQuery('#btnImport').attr("disabled", true);
  }

  if (jQuery('#dbCols').selectedOptions().length > 0 && jQuery('#dataCols').selectedOptions().length > 0) {
    jQuery('#btnMap').attr("disabled", false);
  }
}

function importMappedData() {
  jQuery('#btnImport').addClass('divLoading');
  var filename = jQuery('#uploaded_filename').val();
  var dbMappedOptions = jQuery('#dbMappedCols')[0].options;
  var dataMappedOptions = jQuery('#dataMappedCols')[0].options;
  var len = dbMappedOptions.length;
  var latSpecified = false;
  var lonSpecified = false;
  var mapping = [];
  var atlst1SciTerm = false;
  for (var i = 0; i < len; i++) {
    var obj = new Object();
    if (dbMappedOptions[i].value == 'latitude') {
      latSpecified = true;
    }
    if (dbMappedOptions[i].value == 'longitude') {
      lonSpecified = true;
    }
    if (!atlst1SciTerm) {
      switch (dbMappedOptions[i].value) {
        case 'win_observations.s_kingdom':
        case 'win_observations.s_phylum':
        case 'win_observations.s_class':
        case 'win_observations.s_order':
        case 'win_observations.s_family':
        case 'win_observations.s_genus':
        case 'win_observations.s_species':
          atlst1SciTerm = true;
        break;
      }
    }
    obj.dbcol = dbMappedOptions[i].value;
    obj.datacol = dataMappedOptions[i].value;
    mapping.push(obj);
  }

  if (latSpecified == false || lonSpecified == false) {
    alert('Please specify columns for latitude and longitude columns');
    jQuery('#btnImport').removeClass('divLoading');
    return false;
  }

  if (atlst1SciTerm == false) {
    alert('Please specify atleast one column corresponding to a scientific term that identifies the species.');
    jQuery('#btnImport').removeClass('divLoading');
    return false;
  }

  var data = new Object();
  data.filename = filename;
  data.delimiter = jQuery('#delimiter').val();
  data.enclosure = jQuery('#enclosure').val();
  data.mapping = mapping;

  var obj = new Object();
  obj.action = 'importBulkData';
  obj.params = data;
  var json_data = JSON.stringify(obj);

  var url = Drupal.settings.basePath + 'observation/data';
  jQuery.get(
    url,
    {request: json_data},
    function(data) {
      jQuery('#btnImport').removeClass('divLoading');
      if (parseInt(data.error) == 1) {
        alert(data.msg);
        return false;
      } else {
        /*
        url = Drupal.settings.basePath + 'observation/' + data.observation_id;
        window.location.replace(url);
        */
        jQuery('#divBulkDataMapping').dialog('close');
        alert(data.msg);
        return false;
      }
    },
    'json'
  );

}

function moveSelectedOptionToAnotherSelect(src_select_id, dst_select_id) {
  var ddl_dbCols = jQuery('#' + src_select_id);
  var selOptions = ddl_dbCols.selectedOptions();
  if (selOptions.length == 0) {
    return;
  }
  var dbColOpt = selOptions[0];
  ddl_dbCols.removeOption(ddl_dbCols[0].selectedIndex);

  jQuery('#' + dst_select_id).addOption(dbColOpt.value, dbColOpt.text);
}

jQuery(document).ready(function(){
  var $dialog = jQuery("#divBulkUpload");
  $dialog.dialog({
    autoOpen: false,
    modal: true,
    minWidth: 350,
    minHeight: 175,
    maxWidth: 1200,
    maxHeight: 500,
    width: 350,
    height: 175
  });

  jQuery('#btnBulkUpload').click(function() {
		$dialog.dialog('open');
	});

  jQuery('#divBulkDataMapping').dialog({
    autoOpen: false,
    modal: true,
    minWidth: 650,
    minHeight: 400,
    maxWidth: 1200,
    maxHeight: 500,
    width: 650,
    height: 400
  });

  // bind to the form's submit event
  jQuery('#bulkuploadform').submit(submitBulkUploadForm);

  // Sync the Mapped columns dropdowns
  jQuery('#dbMappedCols').change(function() {
    jQuery('#dataMappedCols')[0].selectedIndex = jQuery('#dbMappedCols')[0].selectedIndex;
  });
  jQuery('#dataMappedCols').change(function() {
    jQuery('#dbMappedCols')[0].selectedIndex = jQuery('#dataMappedCols')[0].selectedIndex;
  });

  jQuery('#btnMap').click(mapColumns);
  jQuery('#btnUnmap').click(unmapColumns);
  jQuery('#btnImport').click(importMappedData);
});